package com.hxzy.config.security;

import cn.hutool.core.util.StrUtil;
import com.hxzy.common.consts.RedisConst;
import com.hxzy.common.enums.AckCode;
import com.hxzy.service.system.impl.TokenService;
import com.hxzy.util.ServletUtil;
import com.hxzy.vo.AdminLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 重写spring security登出操作代码
 */
@Component
public class JwtTokenLogoutHandler  implements LogoutSuccessHandler {

    @Autowired
    private TokenService  tokenService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        String jwtToken=request.getHeader("Authorization");

        if(StrUtil.isNotBlank(jwtToken)){
            AdminLoginVO adminLoginVO = this.tokenService.validatorToken(jwtToken);
            if(adminLoginVO!=null){
                String redisKey= RedisConst.getRedisKey(RedisConst.ADMIN_LOGIN_KEY, adminLoginVO.getUuid());
                //删除String key
                this.redisTemplate.delete(redisKey);
                //删除hash中的值
                this.redisTemplate.opsForHash().delete(RedisConst.ADMIN_LOGIN_ALL, adminLoginVO.getSysUser().getUserId()+"");
            }
        }

        //输出json成功
        ServletUtil.outJson(AckCode.LOGOUT_SUCCESS);
    }
}
